//
//  UIButton+Indicator.swift
//  ADKit
//
//  Created by Adoma on 2020/10/22.
//

import UIKit

private var kIndicatorStyleKey: UInt8 = 0
private var kButtonClickCountKey: UInt8 = 0
private var kButtonTextObjectKey: UInt8 = 0
private var kIndicatorViewKey: UInt8 = 0
private var kIndicatorWidthConstraintKey: UInt8 = 0

extension UIButton {
    
    public var style: UIActivityIndicatorView.Style {
        set {
            objc_setAssociatedObject(self, &kIndicatorStyleKey, "\(newValue.rawValue)", .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            guard let value = objc_getAssociatedObject(self, &kIndicatorStyleKey) as? String,
                  let style = UIActivityIndicatorView.Style.init(rawValue: Int(value)!) else {
                return .gray
            }
            return style
        }
    }
    
    /// by ADKit
    public var isShowIndicator: Bool {
        return clickCount > 0
    }
    
    var clickCount: Int {
        set {
            objc_setAssociatedObject(self, &kButtonClickCountKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, &kButtonClickCountKey) as? Int ?? 0
        }
    }

    /// by ADKit
    public func showIndicator() {
        
        clickCount += 1
        if clickCount > 1 {
            return
        }
        
        let indicator = UIActivityIndicatorView.init(style: style)
        indicator.center = .init(x: self.bounds.width/2, y: self.bounds.height/2)
        indicator.startAnimating()
        
        let currentText = self.titleLabel?.text
        
        objc_setAssociatedObject(self, &kButtonTextObjectKey, currentText, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        
        objc_setAssociatedObject(self, &kIndicatorViewKey, indicator, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                
        let widthConstraint = NSLayoutConstraint.init(item: self, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.frame.width)
        objc_setAssociatedObject(self, &kIndicatorWidthConstraintKey, widthConstraint, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        
        self.addConstraint(widthConstraint)
        self.setTitle("", for: .normal)
        self.addSubview(indicator)
        
    }
    
    public func hideIndicator() {
        
        clickCount -= 1
        if clickCount > 0 {
            return
        }
        
        if let indicator = objc_getAssociatedObject(self, &kIndicatorViewKey) as? UIActivityIndicatorView {
            indicator.removeFromSuperview()
        }
        
        if let widthConstrint = objc_getAssociatedObject(self, &kIndicatorWidthConstraintKey) as? NSLayoutConstraint {
            self.removeConstraint(widthConstrint)
        }
        
        let currentText = objc_getAssociatedObject(self, &kButtonTextObjectKey) as? String
        self.setTitle(currentText, for: .normal)
                
    }
    
}
